let cf = require("/config.js");
var regeneratorRuntime = require("./lib/js/runtime-module.js")
var event = require('./utils/event.js')

import Serv from './appServ';
import Request from "./utils/request";
var util = require("./utils/util.js");


// webim
var webim = require('/data_file/webim.js');
var webimhandler = require('/data_file/webim_handler.js');

var pageCtx;
var newMsgTimer;
let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
global.webim = webim;
global.webimhandler = webimhandler;
var inter;


//埋点收集
var collectData = require("./utils/collectData.js")
App({
  //游戏添加用户
  async addUser(gameActivityId,cbOk){
    let that = this;
    let defualtHeard = 'https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/card/card_defaultImg.png';
    let userInfo = wx.getStorageSync('userInfo')
    let userData = wx.getStorageSync('userData')
    let {city,cityadcode,province,provinceCode} = this.globalData.cityData||""
    let pamars = {
      nickname:userInfo.nickName||'游客',
      mobilePhone:userData.mobile||wx.getStorageSync('phoneNo'),
      headPortraitUrl:userData.avatarUrl||userInfo.avatarUrl||defualtHeard,
      gameActivityId:gameActivityId,
      sourceApp:'置业神器',
      cityName:city||'',
      cityCode:cityadcode||'',
      province:province||'',
      provinceCode:provinceCode||''
    }
    let {success,message,code} = await Serv.addUserServ(pamars)
    if(!success&&code!=401){
      that.globalData.isAddUserSuccess = false
      wx.showToast({
        title: message,
        icon: 'none',
        duration: 5000
      })
    }else{
      that.globalData.isAddUserSuccess = true
      !!cbOk&&cbOk()
    }
  },
  //下单发送模版消息
  sendOrderProgressNotice(id, selectRoomNum, downPayment, messgae, projectName) {
    let activityType = wx.getStorageSync('activityType');
    let openId = wx.getStorageSync('openId');
    let param = {
      page: `/subPackages/pages/HousingActivity/HousingChiXiaoOrderDetail/HousingChiXiaoOrderDetail?type=${activityType}&&id=${id}`,
      toOpenId: openId,
      orderNumber: selectRoomNum,
      orderAmount: "¥" + downPayment,
      orderStatus: messgae,
      orderDetails: projectName,
      reminder: '感谢您对美的置业的支持'
    }
    Serv.sendOrderProgressNotice(param);
  },
  //订阅消息
  subscribeMessage(cb, templateId) {
    let that = this;
    let recordCount = wx.getStorageSync('recordCount');
    if (wx.requestSubscribeMessage) {
      Serv.getTemplateList({ status: 1 }).then((list) => {

        let existTmps = list.model.list.findIndex((item) => item.tplId == templateId)
        if (existTmps >= 0) {
          wx.requestSubscribeMessage({
            tmplIds: [templateId],
            success(res) {
              //判断是否所有消息都已订阅，引导开启未订阅消息
              if (that.checkAllAccept(res, [templateId])) {
                if (cb) cb();
              } else {
                //引导开启
                that.showModel('是否开启所有订阅', '检测到含有未开启订阅，\n是否去开启所有订阅？')
              }
            }, fail(res) {
              //引导询问开启消息订阅
              if (res.errCode == 20004) {
                that.showModel('是否授权开启消息订阅', '为了能够准确通知您的咨询情况，请点击确认', () => {
                  if (cb) cb();
                });
              } else {
                wx.showToast({
                  title: '订阅失效'
                })
                if (cb) cb();
              }

            }
          });
        } else {
          if (cb) cb();
        }

      });

    } else {
      if (!recordCount) {
        //兼容处理
        wx.showModal({
          title: '提示',
          content: '当前微信版本过低，无法使用\n订阅消息功能，请升级到\n最新微信版本后重试。',
          success(res) {
            if (res.confirm) {
              if (cb) cb();
            } else if (res.cancel) {
              if (cb) cb();
            }
          }
        });
        that.recordBehavior()
      } else {
        if (cb) cb();
      }

    }
  },
  //记录用户行为
  recordBehavior() {
    let recordCount = wx.getStorageSync('recordCount') || 0;
    recordCount += 1
    wx.setStorageSync('recordCount', recordCount)
  },
  //引导用户开启
  showModel(titleStr, contentStr, cb) {
    wx.showModal({
      title: titleStr,
      content: contentStr,
      success(res) {
        if (res.cancel) {
          if (cb) cb();
        } else {
          wx.openSetting({})
        }
      }
    })
  },
  //判断是否订阅所有消息
  checkAllAccept(res, id) {
    if (id.length > 0) {
      id.forEach(ele => {
        if (!res[ele]) {
          return false;
        }
      });
      return true;
    }
  },
  onLaunch: function (options) {

    /**
    * 计算顶部高度
    */
    let menuButtonObject = wx.getMenuButtonBoundingClientRect();
    wx.getSystemInfo({
      success: res => {
        let statusBarHeight = res.statusBarHeight,
          navTop = menuButtonObject.top,//胶囊按钮与顶部的距离
          navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;//导航高度
        if (0 <= res.model.indexOf("iPhone X")) {
          navHeight = navHeight + 9
        }
        this.globalData.navHeight = navHeight;
        this.globalData.navTop = navTop;
        this.globalData.windowHeight = res.windowHeight;
      },
      fail(err) {
        console.log(err);
      }
    })
    //拉取代码更新
    this.updateLatestWx();
    //调用API从本地缓存中获取数据
    let that = this;
    this.globalData.code = options
    if (options) {
      that.referrerInfo = JSON.stringify(options);
    }
    //授权访问用户地址
    wx.authorize({
      scope: "scope.userLocation",
      success: (res) => {
        if (!this.globalData.cityData) this.getLocation();


      },
      fail: (error) => {
        if (this.employIdCallback) this.employIdCallback();
      }
    });
    //是否授权
    wx.getSetting({
      withSubscriptions: true,
      success: function (e) {
        let authSetting = e.authSetting;
        let subscriptionsSetting = e.subscriptionsSetting
        that.globalData.isUserInfoAuth = authSetting['scope.userInfo'] || false;
        that.globalData.scriptionNoticeStatus = subscriptionsSetting ? false : true;
      }
    });

    // 为了满足客户的需要，将名片两个字自定义
    that.globalData.cardTitle = "名片"
    wx.getSystemInfo({
      success: function (res) {
        if (0 <= res.model.indexOf("iPhone X")) {
          that.globalData.isIPhoneX = true;
          that.globalData.xStyle = 'padding-bottom:34rpx;'
        }
      }
    });
    //获取用户场景值
    wx.onAppShow(res => {
      
      let channelWxacode = wx.getStorageSync('channelWxacode');
      if (res.query && res.query.sourceChannel) {
        wx.setStorageSync('register_channel_code', res.query.sourceChannel);
        //收集点击外部系统信息
        that.globalData.sensors.track('1100', {});
      }
      wx.removeStorageSync('preLoadImg')
      if (res.scene) {
        this.globalData.latest_scene = res.scene;
        if (res.query.scene) {
          if (res.scene == '1047' || res.scene == '1048' || res.scene == '1049') {
            this.globalData.code = res
            if(channelWxacode)return; //直播二维码不执行下面方法
            if (JSON.stringify(this.globalData.code.query) === "{}") {
              let query = `scene=${this.globalData.code.scene}`
              if (wx.getStorageSync('authName')) {
                this.getSceneLog(query)
              }
            } else {
              this.getStatus(this.globalData.code.query.scene || this.globalData.code.query.id)
            }
          }
        }
      }
      this.counDown(this)
    })


  },

  async getStatus(id) {
    let { success, data } = await Serv.qrcodeStatus({ id })
    if (success) {
      let params = `scene=${this.globalData.code.scene}&param=${this.globalData.code.query.scene}`
      if (JSON.stringify(data) !== "{}" && data.status == false) {
        console.log(data)
        wx.reLaunch({
          url: "/subPackages/pages/loseEfficacy/loseEfficacy",
        })
      } else {
        if (data.id == id) {
          this.globalData.href = null
          this.globalData.channelName = data.channelName;
          if (data.jumpUrl.indexOf('buildingDetail') != -1) {//外链
            console.log(`/${data.jumpUrl}?productId=${data.productId}`)
            wx.reLaunch({
              url: `/${data.jumpUrl}?productId=${data.productId}`,
            })
          } else if (data.jumpUrl.indexOf('http') != -1) {
            console.log(`/${data.jumpUrl}?productId=${data.productId}`)
            wx.switchTab({
              url: `/pages/biz/index/index?positionId=${data.jumpUrl}`,
            })
            this.globalData.href = data.jumpUrl
            // wx.navigateTo({
            //   url: `/pages/biz/h5/h5?href=${encodeURIComponent(data.jumpUrl)}`,
            // })
          }
        }
        if (wx.getStorageSync('authName')) {
          params = `scene=${this.globalData.code.scene}&param=${data.id}`
          this.getSceneLog(params)
        }
        this.globalData.code = { ...this.globalData.code, query: data }
        let req = {
          id: this.globalData.code.query.id,
          type: 1
        }
        this.visitNum(req)
      }
    }
  },
  async  getSceneLog(query) {
    // let query = ''
    // if (JSON.stringify(this.globalData.scene.query) === "{}") {
    //   query = `scene=${this.globalData.scene.scene}`
    // } else {
    //   query = `scene=${this.globalData.scene.scene}&param=${this.globalData.scene.query.productId}`
    // }
    let result = await Serv.getSceneLog(query)
  },
  async visitNum(params) {
    console.log(params)
    let { success } = await Serv.visitNum(params)
  },
  //检查版本更新
  updateLatestWx() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '提示',
              content: '检查到有新版本，但下载失败，请检查网络设置',
              showCancel: false,
            })
          })
        }
      })
    }
  },
  /*//获取公司信息*/
  getCompanyInfo() {
    // if (wx.getStorageSync('companyInfo')) {
    //   return Promise.resolve();
    // }
    let app = getApp();
    return new Promise(function (resolve, reject) {
      wx.request({
        url: cf.config.pageDomain + "applet/mobile/visitcard/account/queryAccount",
        data: {
          cusmallToken: wx.getStorageSync('cusmallToken')
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          var data = res.data;
          if (data && 0 === data.ret) {
            if (data.model.result.extend) {
              data.model.result.extend = JSON.parse(data.model.result.extend);
            }
            wx.setStorageSync("showExpireModal", data.model.expire);
            wx.setStorageSync("companyInfo", data.model.result);
            wx.setStorageSync("privilege", data.model.privilege);
            if (!data.model.visitCardConfig) {
              data.model.visitCardConfig = {};
            }
            if (data.model.cusTheme_1) {
              app.globalData.cardTitle = "AI场景"
            }

            wx.setStorageSync("visitCardConfig", data.model.visitCardConfig);
            if (data.model.visitCardConfig.menuConfig && pageCtx.data.botMenus) {
              if (JSON.parse(data.model.visitCardConfig.menuConfig)) {
                // pageCtx.data.botMenus.list = JSON.parse(data.model.visitCardConfig.menuConfig);
              }
            }
            var skinStyle = {
              "bg": { "type": "1", "bgColor": "#f7f7f7", "bgPic": "" },
              "cardBg": { "startColor": "#488bff", "endColor": "#64cffe" },
              "btnBg": { "startColor": "#3091f2", "endColor": "#3eaeff" },
              "likePic": "",
              "myPic": "",
              "chatPic": "",
              "themeColor": "#3091F2"
            };
            if (data.model.visitCardConfig.skinStyle && JSON.parse(data.model.visitCardConfig.skinStyle)) {
              skinStyle = JSON.parse(data.model.visitCardConfig.skinStyle);
            }
            if (!skinStyle.btnBg.startColor) { skinStyle.btnBg.startColor = "#3091f2" }
            if (!skinStyle.btnBg.endColor) { skinStyle.btnBg.endColor = "#3eaeff" }
            if (!skinStyle.cardBg.startColor) { skinStyle.cardBg.startColor = "#488bff" }
            if (!skinStyle.cardBg.endColor) { skinStyle.cardBg.endColor = "#64cffe" }
            if (!skinStyle.bg.bgColor) { skinStyle.bg.bgColor = "#f7f7f7" }
            if (!skinStyle.themeColor) { skinStyle.themeColor = "#3091F2" }
            pageCtx.setData({
              skinStyle: skinStyle
            })

          }
        },
        fail() {

        },
        complete() {
          resolve();
        }
      });
    });

  },

  /*//获取广告信息*/
  getAdInfo() {
    // if(wx.getStorageSync('advertConfig')){
    //   return Promise.resolve();
    // }
    return new Promise(function (resolve, reject) {
      wx.request({
        url: cf.config.pageDomain + "/applet/mobile/visitcard/advertconfig/getAdvertConfig",
        data: { cusmallToken: wx.getStorageSync('cusmallToken') },
        header: { 'content-type': 'application/json' },
        success: function (res) {
          var data = res.data;
          if (data && 0 === data.ret) {
            let advertConfig = [];
            if (data.model.advertConfig) {
              advertConfig = JSON.parse(data.model.advertConfig);
            }
            wx.setStorageSync("advertConfig", advertConfig);
            //针对直客账号 广告是否显示
            wx.setStorageSync("adShow", data.model.isShow);
          }
        },
        fail() { },
        complete() { resolve(); }
      });
    })
  },

  /*获取用户信息*/
  getUserInfo: function (pageVm, options, cb) {
    let that = this;
    let app = getApp();
    pageCtx = pageVm;
    let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
    let uid = cf.config.customPack ? cf.config.uid : extConfig.uid;
    that.getCusmallToken(pageVm, options).then(function () {
      app.globalData.userInfo = wx.getStorageSync('userInfo');
      app.globalData.cusmallToken = wx.getStorageSync('cusmallToken');
      let promises = [];
      promises.push(that.queryUserIdentity());
      promises.push(that.getCompanyInfo());
      // 考虑性能，改为不阻塞方式
      // promises.push(that.getAdInfo());
      // if (!app.globalData.userSig){
      //   promises.push(that.getUserIMSign(pageVm));
      // }
      Promise.all(promises).then(function (cbParams) {
        cb(app.globalData.userInfo, cbParams);
        if (getCurrentPages().length > 0) {
          pageVm = getCurrentPages()[getCurrentPages().length - 1];
        }
        pageVm.setData({
          'showExpireModal': wx.getStorageSync('showExpireModal')
        })
        if (pageVm.route.startsWith("pages/sales/")) {
          //获取总的聊天未读数量
          app.getTotalUnreadNum(function (num) {

          });
        } else {
          var eId = wx.getStorageSync('eId');
          //获取和某个销售的未读消息数量
          app.getUnreadNumByEID(eId, function (num) {

          });
          app.getTotalUnreadNum(function (num) {

          });
        }
      });
      that.getAdInfo();

      // 判断是否已经获取客户手机号码
      var visitCardConfig = wx.getStorageSync("visitCardConfig");
      if (!wx.getStorageSync("hasGetCustomMobile")) {
        app.checkExistTel(pageVm, function () {
          pageVm.setData({
            getPhoneNumber: visitCardConfig.authTelEnable && !wx.getStorageSync('hasGetCustomMobile')
          });
        });
      } else {
        app.globalData.hasGetCustomMobile = true;
        pageVm.setData({
          app: app,
          getPhoneNumber: visitCardConfig.authTelEnable && !wx.getStorageSync('hasGetCustomMobile')
        })
      }

    });
  },
  /**获取除自定义标题栏外可视区域高度 */
  setScrollHeight(id) {
    let promise = new Promise((resolve, reject) => {
      let scrollHeight = 0
      wx.getSystemInfo({
        success: function (res) {
          let windowHeight = res.windowHeight
          const query = wx.createSelectorQuery()
          query.select(id).boundingClientRect()
          query.selectViewport().scrollOffset()
          query.exec(function (res) {
            scrollHeight = windowHeight - res[0].height
            if (scrollHeight) {
              resolve(scrollHeight)
            }
          })
        }
      })
    })
    return promise;
  },
  /**获取顾问信息 */
  getEmployeeInfo() {
    var ctx = this;
    let cusmallToken = wx.getStorageSync('cusmallToken');
    let isSales = false;
    return new Promise((resolve, reject) => {
      wx.request({
        url: cf.config.pageDomain + "/applet/mobile/visitcard/employee/getEmployeeInfo",
        data: {
          cusmallToken: cusmallToken
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          var data = res.data;
          var employee = data.model && data.model.employee
          if (employee && employee.deleted == false) {
            if (data && 0 === data.ret && employee && employee.wxBind && (employee.powerSwitch & (Math.pow(2, 0))) != 0) {
              isSales = true
            } else {
              isSales = false
            }
            wx.removeStorageSync("employee");
            wx.setStorageSync("employee", { ...data.model.employee, isSales: isSales });
            resolve();
          } else {
            wx.removeStorageSync("employee");
            resolve();
          }
        },
        fail() {
          resolve();
        },
        complete() { }
      });
    })
  },
  /*获取验证信息*/
  getCusmallToken: function (pageVm, options, cb) {
    let that = this;
    let app = getApp();
    let zmzj_token = wx.getStorageSync('authName');
    let cusmallToken = wx.getStorageSync('cusmallToken');
    let userId = wx.getStorageSync('userId');
    return new Promise(function (resolve, reject) {
      wx.request({
        url: cf.config.pageDomain + 'app/weixin/queryTokenStatus',
        data: {
          token: cusmallToken
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (data) {

          if (data.data) {
            if (zmzj_token) {
              var currentPage = getCurrentPages()[getCurrentPages().length - 1].route;
              var pageName = currentPage.split('/')[currentPage.split('/').length - 1];

              pageVm.setData({
                showModal: false,
                showAuthBox: false
              });
              // token获取成功后立即执行，不依赖其他数据
              if (pageVm.onGetTokenFinish && "function" === typeof (pageVm.onGetTokenFinish)) {
                pageVm.onGetTokenFinish();
              }
              resolve();
              if (cb) cb();
            }
          } else {
            let appName = cf.config.customPack ? cf.config.name : extConfig.name;
            // let appLogo = cf.config.customPack ? cf.config.logo : extConfig.logo;
            let appLogo = cf.config.logo
            app.globalData.appName = appName;
            app.globalData.appLogo = appLogo;
            app.globalData.firstInTips = true;

            pageVm.setData({
              "showAuthBox": true,
              "firstInTips": true,
              appName: appName,
              appLogo: appLogo
            })

            pageVm.userinfoFinishCb = function () {
              app.globalData.userInfo = wx.getStorageSync('userInfo');
              resolve();
              if (cb) cb();
            };

          }
        },
        fail: function (data) {
          console.error("后台接口获取cusmallToken失败", data);
        }
      })
    })

  },

  /*查询用户身份*/
  queryUserIdentity: function (reload) {//获取当前用户信息
    let that = this;
    let app = getApp();
    if (!reload && app.globalData.myOpenid) {
      return Promise.resolve();
    }
    return new Promise(function (resolve, reject) {
      wx.request({
        url: cf.config.pageDomain + "/applet/mobile/distributor/queryUserIdentity",
        data: {
          cusmallToken: wx.getStorageSync('cusmallToken')
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          let data = res.data;
          if (data && 0 == data.ret) {
            app.globalData.isDistributor = data.model.userIdentityVo.isDistributor;
            app.globalData.isOpenDistribution = data.model.userIdentityVo.isOpenDistribution;
            app.globalData.myOpenid = data.model.userIdentityVo.openid;
            app.globalData.State = data.model.userIdentityVo.applyState;
            app.globalData.applyRemark = data.model.userIdentityVo.applyRemark;

            // 缓存颜色主题ID
            app.globalData.themeId = data.model.themeId || 1;
          }
        },
        fail: function () {
        },
        complete: function () {
          resolve();
        }
      });
    });

  },

  /*获取当前用户WEBIM账号信息*/
  getUserIMSign: function (cb) {
    let that = this;
    let accountId = wx.getStorageSync('userId');
    let param = {
      cusmallToken: wx.getStorageSync('cusmallToken')
    }
    let defaultImg = 'https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/card/card_defaultImg.png'
    Serv.getUserIMSign(param).then((res) => {
      if (res && 0 == res.ret) {
        res.model.headUrl = res.model.headUrl ? res.model.headUrl : defaultImg
        res.model.accountId = accountId ? accountId : ''
        wx.setStorageSync('IMUserSignInfo', res.model);
        if (!webim.checkLogin()) {
          that.initIM(function () {
            wx.setStorageSync('userSig', res.model.sign);
          });
          if (cb) cb();
          return;
        }
        if (cb) cb();
      }
    })

  },
  /**获取会话未读数 */
  getAllUnreadNum(type, cb) {
    var that = this;
    var openid = wx.getStorageSync('openId');
    var cusmallToken = wx.getStorageSync('cusmallToken');
    var data = {
      cusmallToken: cusmallToken,
      openid: openid
    }
    if (type) {
      data.type = type
    }
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/chatmsg/getAllUnreadNum",
      data,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        cb && cb(res.data.model.list);
      },
      fail() {

      },
      complete() {
      }
    });
  },
  /*获取未读信息*/
  getUnreadNumByEID: function (eId, cb) {
    if (!eId) {
      return;
    }
    var cusmallToken = wx.getStorageSync('cusmallToken');
    var userSignInfo = wx.getStorageSync("IMUserSignInfo");
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/chatmsg/getUnreadNumWithEid",
      data: {
        cusmallToken: cusmallToken,
        openid: userSignInfo.identifier,
        eid: eId,
        type: '1'
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var unReadNum = res.data.model.unreadNum;
        var hasReadMsg = wx.getStorageSync("has_readmsg_" + eId);
        // 新用户进来默认添加一个未读消息
        if (!hasReadMsg) {
          unReadNum += 1;
        }
        if (unReadNum > 0) {
          pageCtx.setData({
            "card_detail_noread": unReadNum,
            "card_detail_employee": res.data.model.employee,
            "isNewsTip": true
          })
          if (newMsgTimer) {
            clearTimeout(newMsgTimer);
          }
          newMsgTimer = setTimeout(function () {
            pageCtx.setData({
              isNewsTip: false
            })
          }, 3000)
        }
        cb && cb(res.data.model.unreadNum);
      },
      fail() {

      },
      complete() {
      }
    });
  },

  //自定义弹出框，禁止页面滚动
  stopPageScroll: function () {
  },

  /*获取所有未读信息*/
  getTotalUnreadNum: function (cb, ctx) {
    var cusmallToken = wx.getStorageSync('cusmallToken');
    var userSignInfo = wx.getStorageSync("IMUserSignInfo");
    var pageVm = ctx || pageCtx;
    if (getCurrentPages().length > 0) {
      pageVm = getCurrentPages()[getCurrentPages().length - 1];
    }
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/chatmsg/getTotalUnreadNum",
      data: {
        cusmallToken: cusmallToken,
        openid: userSignInfo.identifier
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        pageVm.setData({
          "unread_msg_total_num": res.data.model.memberTotal
        })
        if (res.data.model.employeeTotal > 0) {
          wx.showTabBarRedDot({ index: 2 });
        } else {
          wx.hideTabBarRedDot({ index: 2 });
        }
        cb && cb(res.data.model.total);

      },
      fail() {

      },
      complete() {
      }
    });
  },

  /*检查已经存在的电话*/
  checkExistTel: function (pageVm, cb) {
    if (getCurrentPages().length > 0) {
      pageVm = getCurrentPages()[getCurrentPages().length - 1];
    }
    var cusmallToken = wx.getStorageSync('cusmallToken');
    var app = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/member/checkExistTel",
      data: {
        cusmallToken: cusmallToken
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        app.globalData.hasGetCustomMobile = res.data.model.result;
        if (app.globalData.hasGetCustomMobile) {
          wx.setStorageSync('hasGetCustomMobile', "true");
        }
        pageVm.setData({
          app: app
        })
        cb && cb(res.data);
      },
      fail() {

      },
      complete() {
      }
    });
  },

  /*初始化IM*/
  initIM: function (callback) {
    var that = this;
    var userSignInfo = wx.getStorageSync("IMUserSignInfo");
    //当前用户身份
    var loginInfo = {
      'sdkAppID': userSignInfo.imAppId, //用户所属应用id,必填
      'appIDAt3rd': userSignInfo.imAppId, //用户所属应用id，必填
      'accountType': userSignInfo.imAccountType, //用户所属应用帐号类型，必填
      'identifier': userSignInfo.identifier, //当前用户ID,必须是否字符串类型，选填
      'identifierNick': userSignInfo.nickName, //当前用户昵称，选填
      'userSig': userSignInfo.sign, //当前用户身份凭证，必须是字符串类型，选填
    };

    //监听（多终端同步）群系统消息方法，方法都定义在demo_group_notice.js文件中
    var onGroupSystemNotifys = {
      "5": webimhandler.onDestoryGroupNotify, //群被解散(全员接收)
      "11": webimhandler.onRevokeGroupNotify, //群已被回收(全员接收)
      "255": webimhandler.onCustomGroupNotify//用户自定义通知(默认全员接收)
    };

    //监听连接状态回调变化事件
    var onConnNotify = function (resp) {
      switch (resp.ErrorCode) {
        case webim.CONNECTION_STATUS.ON:
          //webim.Log.warn('连接状态正常...');
          break;
        case webim.CONNECTION_STATUS.OFF:
          webim.Log.warn('连接已断开，无法收到新消息，请检查下你的网络是否正常');
          break;
        default:
          webim.Log.error('未知连接状态,status=' + resp.ErrorCode);
          break;
      }
    };


    //监听事件
    var listeners = {
      "onConnNotify": webimhandler.onConnNotify, //选填
      "onBigGroupMsgNotify": function (msg) {
      }, //监听新消息(大群)事件，必填
      "onMsgNotify": function (newMsgList) {
        

        var r = newMsgList[0].elems[0].content.text;
        var d = JSON.parse(util.chageChatData2(r));
        if (d.msg.type == 16) {

          that.videoCallback = function (callback) { callback('callValue', d) }
          switch (d.msg.coupon.action) {
            // 对方呼叫我
            case 0:
              if (!that.globalData.isCalling) {
                let url = `/subPackages/pages/room/room?args=${JSON.stringify(d.msg.coupon)}&&from=${d.from_userinfo.identifier}&&to=${d.to_userinfo.identifier}`
                wx.navigateTo({ url })
              } else {
                event.emit('isCalling', d);

              }
              break
            // 对方取消
            case 1:
              wx.navigateBack({
                delta: 1
              })
              break
            // 对方拒绝
            case 2:
              event.emit('onRefuse');

              break
            // 对方不接1min
            case 3:
              wx.navigateBack({
                delta: 1
              })
              break
            // 对方接听
            case 4:
              event.emit('onCall', d);

              break
            // 对方挂断
            case 5:
              event.emit('onClose', d);
              break
            // 对方正在通话中
            case 6:
              event.emit('onBusy', d);

              break
            default:
              break
          }

        }
        webimhandler.onMsgNotify(newMsgList);
        //获取总的聊天未读数量
        if (getCurrentPages().length > 0) {
          pageCtx = getCurrentPages()[getCurrentPages().length - 1];
        }
        if (pageCtx.route.startsWith("pages/sales/")) {
          //获取总的聊天未读数量
          that.getTotalUnreadNum(function (num) {

          });
        } else {
          var eId = wx.getStorageSync('eId');
          //获取和某个销售的未读消息数量
          that.getUnreadNumByEID(eId, function (num) {
          });
          that.getTotalUnreadNum(function (num) {

          });
        }
      },//监听新消息(私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息)事件，必填
      "onGroupSystemNotifys": webimhandler.onGroupSystemNotifys, //监听（多终端同步）群系统消息事件，必填
      "onGroupInfoChangeNotify": webimhandler.onGroupInfoChangeNotify//监听群资料变化事件，选填
    };

    //其他对象，选填
    var options = {
      'isAccessFormalEnv': true,//是否访问正式环境，默认访问正式，选填
      'isLogOn': true//是否开启控制台打印日志,默认开启，选填
    };
    //webimhandler.setPageCtx(pageCtx);
    //sdk登录
    webimhandler.sdkLogin(loginInfo, listeners, options, callback);

  },
  //重新授权
  resetLocation(fu) {
    var that = this;
    wx.getSetting({
      success: (res) => {
        if ((res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true)) {//非初始化进入该页面,且未授权
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则无法操作',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success: function (data) {
                    if (data.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 5000
                      })
                      //再次授权，调用getLocationt的API
                      that.getLocation().then(() => {
                        !!fu && fu();
                      });
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 5000
                      })
                    }
                  }
                })
              }
            }
          })
          return;
        } else if (this.globalData.cityData) {
          !!fu && fu();
          return;
        }
        that.getLocation().then(() => {
          !!fu && fu();
        });

      },
      fail: () => {
        !!fu && fu();
      }
    }

    )
  },
  counDown() {
    const that = this;
    var t = 20
    inter = setInterval(function () {
      t--
      if (t <= 0 && (that.globalData && !that.globalData.cityData)) {
        wx.showToast({
          title: '请确认是否已经开启手机定位功能',
          icon: 'none',
          duration: 5000
        })
        clearInterval(inter)
      }else{
        clearInterval(inter)
      }
    }, 1000)
  },
  getLocation() {

    const that = this;
    const type = "公司企业|公共设施住宿服务|风景名胜|商务住宅|政府机构及社会团体|交通设施服务";
    return new Promise(function (resolve, reject) {
      // that.counDown(that)
      wx.getLocation({
        type: 'gcj02',
        altitude: 'true',
        success: function (r) {
          console.log('定位成功');
          Request({
            url: `app/address/getCityAddress`,
            data: {
              lat: r.latitude,
              lng: r.longitude,
              poitype: type,
              channel: '1010'
            },
            headers: {
              "Content-type": "application/x-www-form-urlencoded"
            },
            type: "GET",
          }).then((res) => {
            if (res.success) {
              console.log('定位成功'+JSON.stringify(res));
              clearInterval(inter)
              const data = res.data;
              let city = data.cityName;
              if (city && city.indexOf('市') > -1) {
                city = city.slice(0, -1);
              }
              const cityData = {
                city,
                cityadcode: data.code,
                provinceCode: data.parentCode,
                province: data.parentName,
                lng: data.lng,
                lat: data.lat,
                district: data.district,
                town: data.town,
                street: data.street,
                country: data.country
              }
              that.globalData.cityData = cityData;
              
              if (that.employIdCallback) {
                that.employIdCallback(cityData)
              }
              resolve()
            }else{
              resolve()
              console.log('定位失败'+JSON.stringify(res));
            }
          }).catch((errMsg) => {
            resolve(errMsg)
          });
        },
        fail: function (errMsg) {
          console.log('失败');
          resolve(errMsg)

        }
      })
    })
  },
  // 画布压缩图片 bl为输出剪切后图片的高宽比(高/宽) width为要输出的图片的宽(单位为px) quality为输出图片的质量，范围(0,1],id是页面canvas的id
  drawImage(src, bl = 0.8, quality = 1, width = null, id = 'canvas') {
    const promise = new Promise((resolve, reject) => {
      wx.getImageInfo({
        src,
        success: function (img) {
          width = !width ? img.width : width
          const ctx = wx.createCanvasContext(id)
          ctx.drawImage(img.path, 0, 0, width, width);
          ctx.draw(false, function () {
            wx.canvasToTempFilePath({
              width,
              height: width * bl,
              destWidth: width,
              destHeight: width * bl,
              canvasId: id,
              fileType: 'jpg',
              quality,
              success(res) {
                resolve(res.tempFilePath)
              }
            })
          });
        }
      })
    })
    return promise
  },

  // 拦截非顾问进行顾问操作

  async routerIntercept() {
    let getEmployee = function () {
      return new Promise((resolve, reject) => {
        wx.request({
          url: cf.config.pageDomain + "/applet/mobile/visitcard/employee/getEmployeeInfo",
          data: {
            cusmallToken: wx.getStorageSync('cusmallToken')
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            if (res.data && res.data.model && res.data.model.employee) {
              wx.setStorageSync("employee", { ...wx.getStorageSync('employee'), isSales: true });
              resolve(true)
            } else {
              wx.removeStorageSync("employee");
              resolve(false)
            }
          },
          fail: function (res) {
            resolve(false)
          }
        })
      })
    }
    let flag = await getEmployee()
    if (!flag) {
      wx.navigateTo({
        url: '/pages/load/load',
        success: function () {
          wx.showToast({
            title: '您不是顾问，自动为您跳转名片列表',
            icon: 'none'
          })
          let timer = setTimeout(() => {
            wx.hideToast()
            clearTimeout(timer)
          }, 3000);
        }
      })
    }

  },

  globalData: {
    userInfo: null,
    cusmallToken: null,
    cityData: null,
    buryingPointBuild: null,
    buryingPointBuildObj: {},
    scene: null,
    code: null,
    href: null,
    tokenStatus: true,
    isRead: true,
    messageCount: 0,
    appId: '1010',
    setRouterIntercept: null,
    preloadAllPage: [],
    wxopenActivitySetting: null,
    HousingActivityID: null,
    scriptionNoticeStatus: false,
    isCalling: false,
    WechatLocation: false,
    isAddUserSuccess:false
  },

  onHide: function () {
    clearInterval(inter)
    wx.getBackgroundAudioManager().pause();
  }

})
